
#include<stdio.h> 			/* perror */
#include<stdlib.h>			/* exit	*/
#include<sys/types.h>		/* WNOHANG */
#include<sys/wait.h>		/* waitpid */
#include<string.h>			/* memset */
#include<pthread.h>

#include "socketwrapper.h" 	/* socket layer wrapper */
#include "parser.h"			/* ChatSys PDU parser   */
#include "event.h"
#include "msgq.h"

#include "chatsys.h"

#define	true		1
#define false		0
#define OK			0


int main() 
{
		tChatSysMsg Msg,RspMsg;
		int i;
		int sockfd = CspInit(INIT_AS_CLIENT);
		if(sockfd == FAILURE)
			printf("CspInit failure!\n");
		char str[MAX_NUM_STR];
		printf("Input your name>>");
		fgets(str,MAX_NUM_STR,stdin);
		Msg.Connfd = sockfd;
		Msg.Version = CHAT_SYS_VERSION;
		Msg.MsgType	= MT_LOGIN_MSG;
		memcpy(Msg.Msg,str,strlen(str));
		Msg.MsgLen	= strlen(Msg.Msg);
		CspSend(&Msg);
		pthread_create(RecvMsg);
		while(1)
		{
			printf(">>");
			for(i=0;i<MAX_NUM_STR;i++)
				str[i]='\0';
			fgets(str,MAX_NUM_STR,stdin);
			Msg.Connfd = sockfd;
			Msg.Version = CHAT_SYS_VERSION;
			Msg.MsgType	= MT_CHAT_MSG;
			memcpy(Msg.Msg,str,strlen(str));
			Msg.MsgLen	= strlen(str);			
			Msg.Msg[Msg.MsgLen-1]='\0';
			CspSend(&Msg);
#if 0	
			CspRecv(&RspMsg);
			printf("RspMsg.Connfd:%d\n",RspMsg.Connfd);
		 	printf("RspMsg.Version:%d\n",RspMsg.Version);
			printf("RspMsg.MsgType:%d\n",RspMsg.MsgType);
			printf("RspMsg.SerialNumber:%d\n",RspMsg.SerialNumber);
			printf("RspMsg.MsgLen:%d\n",RspMsg.MsgLen);
			RspMsg.Msg[RspMsg.MsgLen-1]='\0';
			printf("RspMsg.Msg:%s\n",RspMsg.Msg);
#endif
		}
#if 0
		Msg.MsgType	= MT_LOGOUT_MSG;
		CspSend(&Msg);

		CspCloseConnection(sockfd);	
		CspShut();
#endif
		return 0;
}

void RecvMsg()
{
	while(1)
	{
		CspRecv(&RspMsg);
		printf(RspMsg);
	}	
}